package com.dco.dcowebhook.service;

import com.dco.dcowebhook.model.WebhookPayload;
import com.dco.dcowebhook.model.WebhookPayload.InvalidCommit;
import com.dco.dcowebhook.model.WebhookEvent;
import com.dco.dcowebhook.model.InvalidCommitData;
import com.dco.dcowebhook.repository.WebhookEventRepository;
import com.dco.dcowebhook.repository.InvalidCommitRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DataService {

    private final WebhookEventRepository webhookEventRepository;
    private final InvalidCommitRepository invalidCommitRepository;

    @Autowired
    public DataService(WebhookEventRepository webhookEventRepository, InvalidCommitRepository invalidCommitRepository) {
        this.webhookEventRepository = webhookEventRepository;
        this.invalidCommitRepository = invalidCommitRepository;
    }

    /**
     * 插入完整的 Webhook 事件数据。
     *
     * @param payload Webhook 负载数据
     */
    @Transactional
    public void insertWebhookData(WebhookPayload payload) {
        WebhookEvent event = new WebhookEvent();
        event.setRepositoryName(payload.getRepository().getName());
        event.setRepositoryOwner(payload.getRepository().getOwner().getName());
        event.setPusher(payload.getCommits().get(0).getAuthor().getName());
        event.setRef(payload.getRef());
        event.setBefore(payload.getBefore());
        event.setAfter(payload.getAfter());
        event.setReceivedAt(LocalDateTime.now());

        webhookEventRepository.save(event);
    }

    /**
     * 插入未通过 DCO 验证的提交数据。
     *
     * @param invalidCommits 未通过 DCO 验证的提交列表
     */
    @Transactional
    public void insertInvalidCommits(List<InvalidCommit> invalidCommits) {
        for (InvalidCommit commit : invalidCommits) {
            InvalidCommitData commitData = new InvalidCommitData();
            commitData.setSha(commit.getSha());
            commitData.setAuthor(commit.getAuthor());
            commitData.setMessage(commit.getMessage());
            commitData.setUrl(commit.getUrl());
            commitData.setDetectedAt(LocalDateTime.now());

            invalidCommitRepository.save(commitData);
        }
    }
}
